//
//  AddAddressViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/9.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "AddAddressViewController.h"

@interface AddAddressViewController ()<UITableViewDelegate, UITableViewDataSource, UIPickerViewDataSource, UIPickerViewDelegate, UITextFieldDelegate>{
    NSDictionary *_areaDic;//地区字典
    NSArray *_province;//省 数组
    NSArray *_city;//市 数组
    NSArray *_district;//区 数组
    
    NSString *_selectedProvince;//选中的省份
    UIButton *_shadowBtn;//蒙尘效果按钮
    
    NSString *_recProv;//省
    NSString *_recCity;//市
    NSString *_recArea;//区
    
    UITextField *connectField;
    UITextField *phoneField;
    UITextField *addressField;
    UITextField *detailAddressField;
}

@property (nonatomic, strong) BaseTableView *tableView;
@property (nonatomic, strong) UIView *pickViewToobar;//pickview的完成工具条
@property (nonatomic, strong) UIPickerView *pickView;
@property (nonatomic, assign) BOOL isSelect;


@end

@implementation AddAddressViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (_addressModel) {
        self.title = @"修改收货地址";
        self.isSelect = [_addressModel.Default integerValue];
        _recProv = _addressModel.province;
        _recCity = _addressModel.city;
        _recArea = _addressModel.district;
    }else {
        self.title = @"添加收货地址";
        self.isSelect = NO;
    }
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = ScreenX375(44);
    [self.view addSubview:self.tableView];
    
    UIView *operateView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(155))];
    self.tableView.tableFooterView = operateView;
    
    OperateButton *button = [[OperateButton alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(50), SCREEN_WIDTH - ScreenX375(26), ScreenX375(44))];
    [button setTitle:@"保存" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
    [operateView addSubview:button];
    
    [self initWithData];
}

- (void)save {
    if (_recProv.length == 0) {
        [HttpManager showNoteMsg:@"请选择省市区信息"];
        return;
    }
    if (detailAddressField.text.length == 0) {
        [HttpManager showNoteMsg:@"请填写详细地址信息"];
        return;
    }
    if (connectField.text.length == 0) {
        [HttpManager showNoteMsg:@"请填写收货人信息"];
        return;
    }
    if (phoneField.text.length == 0) {
        [HttpManager showNoteMsg:@"请填写手机号信息"];
        return;
    }
    NSString * url = [NSString stringWithFormat:@"%@app/address_insert",REQUESTHEADER];
    NSDictionary * parameter = @{@"token":[FPLoginAndRegisterTools getToken],@"province":_recProv,@"city":_recCity,@"district":_recArea,@"place":detailAddressField.text,@"consignee":connectField.text,@"telephone":phoneField.text,@"default":[NSNumber numberWithBool:_isSelect]};
    if (_addressModel) {
        url = [NSString stringWithFormat:@"%@app/address_update",REQUESTHEADER];
        parameter = @{@"token":[FPLoginAndRegisterTools getToken],@"address_id":_addressModel.Id,@"province":_recProv,@"city":_recCity,@"district":_recArea,@"place":detailAddressField.text,@"consignee":connectField.text,@"telephone":phoneField.text,@"default":[NSNumber numberWithBool:_isSelect]};
    }
    
    [HttpManager showWait];
    [HttpManager postHttpRequestByPost:url andParameter:parameter success:^(id successResponse) {
        [self.tableView.mj_header endRefreshing];
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [HttpManager showNoteMsg:@"新建成功"];
            [kNotificationCenter postNotificationName:@"ReloadAddressList" object:self userInfo:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [HttpManager showFail];
    }];
}

//初始化三级联动地址
- (void)initWithData{
    
    NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"area" ofType:@"plist"];
    _areaDic = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];
    
    NSArray *components = [_areaDic allKeys];
    NSArray *sortedArray = [components sortedArrayUsingComparator: ^(id obj1, id obj2) {
        
        if ([obj1 integerValue] > [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if ([obj1 integerValue] < [obj2 integerValue]) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    
    NSMutableArray *provinceTmp = [[NSMutableArray alloc] init];
    for (int i=0; i<[sortedArray count]; i++) {
        NSString *index = [sortedArray objectAtIndex:i];
        NSArray *tmp = [[_areaDic objectForKey: index] allKeys];
        [provinceTmp addObject: [tmp objectAtIndex:0]];
    }
    
    _province = [[NSArray alloc] initWithArray: provinceTmp];
    
    NSString *index = [sortedArray objectAtIndex:0];
    NSString *selected = [_province objectAtIndex:0];
    NSDictionary *dic = [NSDictionary dictionaryWithDictionary: [[_areaDic objectForKey:index]objectForKey:selected]];
    
    NSArray *cityArray = [dic allKeys];
    NSDictionary *cityDic = [NSDictionary dictionaryWithDictionary: [dic objectForKey: [cityArray objectAtIndex:0]]];
    _city = [[NSArray alloc] initWithArray: [cityDic allKeys]];
    
    
    NSString *selectedCity = [_city objectAtIndex: 0];
    _district = [[NSArray alloc] initWithArray: [cityDic objectForKey: selectedCity]];
    
    _selectedProvince = [_province objectAtIndex: 0];
    
}

- (void)showPickView {
    [self.view endEditing:YES];
    if (!_pickView){
        _recProv = @"北京市";
        _recCity = @"北京市";
        _recArea = @"东城区";
        
        //工具条
        _pickViewToobar = [[UIView alloc]initWithFrame:CGRectMake(0,SCREEN_HEIGHT, SCREEN_WIDTH, 44)];
        _pickViewToobar.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_pickViewToobar];
        
        UIButton *cancleBtn = [[UIButton alloc]initWithFrame:CGRectMake(20, 0, 40, _pickViewToobar.frame.size.height)];
        [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
        [cancleBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
        [cancleBtn addTarget:self action:@selector(pickViewOperateClick:) forControlEvents:UIControlEventTouchUpInside];
        [_pickViewToobar addSubview:cancleBtn];
        
        UIButton *achiveBtn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 50, 0, 40, _pickViewToobar.frame.size.height)];
        [achiveBtn setTitle:@"完成" forState:UIControlStateNormal];
        achiveBtn.tag = 1;
        [achiveBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
        [achiveBtn addTarget:self action:@selector(pickViewOperateClick:) forControlEvents:UIControlEventTouchUpInside];
        [_pickViewToobar addSubview:achiveBtn];
        
        _shadowBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - TAB_BAR_HEIGHT)];
        [_shadowBtn setBackgroundColor:RGBACOLOR(49, 49, 49, 0.6)];
        [_shadowBtn addTarget:self action:@selector(hiddenPickView) forControlEvents:UIControlEventTouchUpInside];
        [_tableView addSubview:_shadowBtn];
        
        _pickView = [[UIPickerView alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(_pickViewToobar.frame), SCREEN_WIDTH, 162)];
        _pickView.delegate = self;
        _pickView.dataSource = self;
        _pickView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:_pickView];
    }
    
    //判断pickerView的位置
    if (_pickView.frame.origin.y == SCREEN_HEIGHT+44) {
        
        [UIView animateWithDuration:0.3 animations:^{
            
            self->_pickView.frame = CGRectMake(0, SCREEN_HEIGHT - 162 - NAVIGATION_BAR_HEIGHT, SCREEN_WIDTH, 162);
            self->_tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-162 - NAVIGATION_BAR_HEIGHT - TAB_BAR_HEIGHT);
            self->_pickViewToobar.frame = CGRectMake(0,CGRectGetMinY(self->_pickView.frame)-44, SCREEN_WIDTH, 44);
        }];
        _shadowBtn.hidden = NO;
        
    }else{
        
        [UIView animateWithDuration:0.3 animations:^{
            self->_pickView.frame = CGRectMake(0, CGRectGetMaxY(self->_pickViewToobar.frame), SCREEN_WIDTH, 162);
            self->_pickViewToobar.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44);
        }];
        _shadowBtn.hidden = YES;
    }
}

//隐藏时间选择器
- (void)hiddenPickView{
    
    [UIView animateWithDuration:0.3 animations:^{
        
        self->_pickViewToobar.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 44);
        self->_pickView.frame = CGRectMake(0, CGRectGetMaxY(self->_pickViewToobar.frame), SCREEN_WIDTH, 162);
    }];
    _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    
    _shadowBtn.hidden = YES;
}

//点击pickView的工具条操作按钮
- (void)pickViewOperateClick:(UIButton *)sender{
    
    if (sender.tag == 1) {
        //完成
        addressField.text = [NSString stringWithFormat:@"%@ %@ %@",_recProv,_recCity,_recArea];
        [self hiddenPickView];
    }else{
        //取消
        [self hiddenPickView];
    }
}

#pragma mark - UITableView;

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 2;
    }
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            static NSString *cellId = @"connectCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
                UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), 0, ScreenX375(80), ScreenX375(46))];
                noteLabel.text = @"收 件 人：";
                noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
                noteLabel.font = Kfont(14);
                [cell addSubview:noteLabel];
                
                connectField = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(86), 0, SCREEN_WIDTH - ScreenX375(110), ScreenX375(46))];
                connectField.placeholder = @"填写收件人";
                connectField.font = Kfont(14);
                connectField.returnKeyType = UIReturnKeyDone;
                connectField.delegate = self;
                if (_addressModel) {
                    connectField.text = _addressModel.consignee;
                }
                [cell addSubview:connectField];
                
                UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(46) - 0.5, SCREEN_WIDTH - ScreenX375(26), 0.5)];
                line.image = [UIImage imageNamed:@"虚线"];
                [cell addSubview:line];
            }
            return cell;
        }else {
            static NSString *cellId = @"phoneCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
                UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), 0, ScreenX375(80), ScreenX375(46))];
                noteLabel.text = @"联系电话：";
                noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
                noteLabel.font = Kfont(14);
                [cell addSubview:noteLabel];
                
                phoneField = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(86), 0, SCREEN_WIDTH - ScreenX375(110), ScreenX375(46))];
                phoneField.placeholder = @"填写联系电话";
                phoneField.font = Kfont(14);
                phoneField.returnKeyType = UIReturnKeyDone;
                phoneField.delegate = self;
                phoneField.keyboardType = UIKeyboardTypePhonePad;
                if (_addressModel) {
                    phoneField.text = _addressModel.telephone;
                }
                [cell addSubview:phoneField];
                
            }
            return cell;
        }
    }else {
        if (indexPath.row == 0) {
            static NSString *cellId = @"addressCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                
                UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), 0, ScreenX375(80), ScreenX375(46))];
                noteLabel.text = @"所在地区：";
                noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
                noteLabel.font = Kfont(14);
                [cell addSubview:noteLabel];
                
                addressField = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(86), 0, SCREEN_WIDTH - ScreenX375(110), ScreenX375(46))];
                addressField.placeholder = @"请选择所在地区";
                addressField.font = Kfont(14);
                if (_addressModel) {
                    addressField.text = [NSString stringWithFormat:@"%@ %@ %@",_addressModel.province,_addressModel.city,_addressModel.district];
                }
                [cell addSubview:addressField];
                
                UIButton *selectAddress = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(86), 0, SCREEN_WIDTH - ScreenX375(110), ScreenX375(46))];
                selectAddress.backgroundColor = [UIColor clearColor];
                [selectAddress addTarget:self action:@selector(showPickView) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:selectAddress];
                
                UIImageView *line = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(46) - 0.5, SCREEN_WIDTH - ScreenX375(26), 0.5)];
                line.image = [UIImage imageNamed:@"虚线"];
                [cell addSubview:line];
            }
            return cell;
        }else if (indexPath.row == 1) {
            static NSString *cellId = @"detailAddressCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
                UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), 0, ScreenX375(80), ScreenX375(46))];
                noteLabel.text = @"详细地址：";
                noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
                noteLabel.font = Kfont(14);
                [cell addSubview:noteLabel];
                
                detailAddressField = [[UITextField alloc] initWithFrame:CGRectMake(ScreenX375(86), 0, SCREEN_WIDTH - ScreenX375(110), ScreenX375(46))];
                detailAddressField.placeholder = @"填写详细地址";
                detailAddressField.font = Kfont(14);
                detailAddressField.returnKeyType = UIReturnKeyDone;
                detailAddressField.delegate = self;
                if (_addressModel) {
                    detailAddressField.text = _addressModel.place;
                }
                [cell addSubview:detailAddressField];
                
                UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(46) - 0.5, SCREEN_WIDTH, 0.5)];
                line.backgroundColor = LineColor;
                [cell addSubview:line];
            }
            return cell;
        }else {
            static NSString *cellId = @"selectCell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                
                UIButton *selectBtn = [[UIButton alloc] initWithFrame:CGRectMake(ScreenX375(11), 13 * SCREEN_WIDTH / 375, 100 * SCREEN_WIDTH / 375, 18 * SCREEN_WIDTH / 375)];
                [selectBtn setTitle:@" 设为默认地址" forState:UIControlStateNormal];
                [selectBtn setTitleColor:FONTCOLOR_BLACK forState:UIControlStateNormal];
                selectBtn.titleLabel.font = [UIFont systemFontOfSize:13 * SCREEN_WIDTH / 375];
                if (!_isSelect) {
                    [selectBtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
                }else {
                    [selectBtn setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateNormal];
                }
                [selectBtn addTarget:self action:@selector(selectClick:) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:selectBtn];
            }
            return cell;
        }
    }
}

- (void)selectClick:(UIButton *)button {
    if (!_isSelect) {
        [button setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateNormal];
    }else {
        [button setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
    }
    _isSelect = !_isSelect;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return ScreenX375(53);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return ScreenX375(10);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(53))];
    view.backgroundColor = [UIColor whiteColor];
    
    UIView *rline = [[UIView alloc] initWithFrame:CGRectMake(0, ScreenX375(15), ScreenX375(3), ScreenX375(23))];
    rline.backgroundColor = ThemeColor;
    [view addSubview:rline];
    
    UILabel *noteLabel = [[UILabel alloc] initWithFrame:CGRectMake(ScreenX375(13), ScreenX375(15), ScreenX375(200), ScreenX375(24))];
    noteLabel.text = section == 0 ? @"个人信息" : @"收货地址";
    noteLabel.textColor = REXADECIMALCOLOR(@"#333333");
    noteLabel.font = Kfont(18);
    [view addSubview:noteLabel];
    
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, ScreenX375(53) - 0.5, SCREEN_WIDTH, 0.5)];
    line.backgroundColor = LineColor;
    [view addSubview:line];
    
    return view;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, ScreenX375(10))];
    view.backgroundColor = TABLEVIEW_BACKGROUNDCOLOR;
    return view;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    return NO;
}

#pragma mark - UIPickView 数据源代理方法
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    
    if (component == 0) {
        
        return [_province count];
    }else if (component == 1){
        
        return [_city count];
    }else if (component == 2){
        
        return [_district count];
    }
    return 4;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    
    if (component == 0) {
        return [_province objectAtIndex: row];
    }else if (component == 1){
        return [_city objectAtIndex: row];
    }else if (component == 2){
        return [_district objectAtIndex: row];
    }
    return @" ";
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    //让三级联动，存在关系跳转
    if (component == 0) {
        _selectedProvince = [_province objectAtIndex: row];
        NSDictionary *tmp = [NSDictionary dictionaryWithDictionary: [_areaDic objectForKey: [NSString stringWithFormat:@"%ld", (long)row]]];
        NSDictionary *dic = [NSDictionary dictionaryWithDictionary: [tmp objectForKey: _selectedProvince]];
        NSArray *cityArray = [dic allKeys];
        NSArray *sortedArray = [cityArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
            
            if ([obj1 integerValue] > [obj2 integerValue]) {
                return (NSComparisonResult)NSOrderedDescending;//递减
            }
            
            if ([obj1 integerValue] < [obj2 integerValue]) {
                return (NSComparisonResult)NSOrderedAscending;//上升
            }
            return (NSComparisonResult)NSOrderedSame;
        }];
        
        NSMutableArray *array = [[NSMutableArray alloc] init];
        for (int i=0; i<[sortedArray count]; i++) {
            NSString *index = [sortedArray objectAtIndex:i];
            NSArray *temp = [[dic objectForKey: index] allKeys];
            [array addObject: [temp objectAtIndex:0]];
        }
        
        _city = [[NSArray alloc] initWithArray: array];
        
        NSDictionary *cityDic = [dic objectForKey: [sortedArray objectAtIndex: 0]];
        _district = [[NSArray alloc] initWithArray: [cityDic objectForKey: [_city objectAtIndex: 0]]];
        [_pickView selectRow: 0 inComponent: 1 animated: YES];
        [_pickView selectRow: 0 inComponent: 2 animated: YES];
        [_pickView reloadComponent: 1];
        [_pickView reloadComponent: 2];
        
    }
    else if (component == 1) {
        NSString *provinceIndex = [NSString stringWithFormat: @"%lu", (unsigned long)[_province indexOfObject: _selectedProvince]];
        NSDictionary *tmp = [NSDictionary dictionaryWithDictionary: [_areaDic objectForKey: provinceIndex]];
        NSDictionary *dic = [NSDictionary dictionaryWithDictionary: [tmp objectForKey: _selectedProvince]];
        NSArray *dicKeyArray = [dic allKeys];
        NSArray *sortedArray = [dicKeyArray sortedArrayUsingComparator: ^(id obj1, id obj2) {
            
            if ([obj1 integerValue] > [obj2 integerValue]) {
                return (NSComparisonResult)NSOrderedDescending;
            }
            
            if ([obj1 integerValue] < [obj2 integerValue]) {
                return (NSComparisonResult)NSOrderedAscending;
            }
            return (NSComparisonResult)NSOrderedSame;
        }];
        
        NSDictionary *cityDic = [NSDictionary dictionaryWithDictionary: [dic objectForKey: [sortedArray objectAtIndex: row]]];
        NSArray *cityKeyArray = [cityDic allKeys];
        
        _district = [[NSArray alloc] initWithArray: [cityDic objectForKey: [cityKeyArray objectAtIndex:0]]];
        [_pickView selectRow: 0 inComponent: 2 animated: YES];
        [_pickView reloadComponent: 2];
    }
    
    //获得当前选中的城市
    
    NSInteger provinceIndex = [_pickView selectedRowInComponent:0];
    NSInteger cityIndex = [_pickView selectedRowInComponent:1];
    NSInteger districtIndex = [_pickView selectedRowInComponent:2];
    
    NSString *provinceStr = [_province objectAtIndex: provinceIndex];
    NSString *cityStr = [_city objectAtIndex: cityIndex];
    NSString *districtStr = [_district objectAtIndex:districtIndex];
    
    if ([provinceStr isEqualToString: cityStr] && [cityStr isEqualToString: districtStr]) {
        cityStr = @"";
        districtStr = @"";
    }
    else if ([cityStr isEqualToString: districtStr]) {
        districtStr = @"";
    }
    
    _recProv = provinceStr;
    _recCity = cityStr;
    _recArea = districtStr;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    if (component == 0) {
        return 100;
    }
    else if (component == 1) {
        return 100;
    }
    else {
        return 115;
    }
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    
    return 35.0f;
    
}

- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    if (!view){
        view = [[UIView alloc]init];
    }
    CGFloat width = 100.0;
    if (component == 2) {
        width = 115.0;
    }
    
    UILabel *text = [[UILabel alloc] initWithFrame:CGRectMake(0.0, 0.0, width, 35)];
    text.font = Kfont(17);
    if (component == 0) {
        text.text = [_province objectAtIndex:row];
    }
    else if (component == 1) {
        text.textAlignment = NSTextAlignmentCenter;
        text.text = [_city objectAtIndex:row];
    }
    else {
        text.textAlignment = NSTextAlignmentRight;
        text.text = [_district objectAtIndex:row];
    }
    [view addSubview:text];
    
    return view;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
